package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import jodd.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Author：Chunk
 * @Description:
 * @Date Created in 13:41 2021/4/21
 */
@Slf4j
@org.springframework.stereotype.Service
@Service
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private UserVerifyMapper userVerifyMapper;
    @Autowired
    MailSender mailSender;
    /*
    * @Author Chunk
    * @Description
    * @Date 14:36 2021/4/21
    * @Param [registerRequest]
    * @return com.mall.user.dto.UserRegisterResponse
    **/
    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
        UserRegisterResponse response = new UserRegisterResponse();
        //判空验证
        registerRequest.requestCheck();
        //验证用户名是否重复
        try {
            validUserNameRepeat(registerRequest);
        } catch (Exception e) {
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            response.setCode(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode());
            response.setMsg(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
            return response;
        }
        //向用户表中插入一条记录
        Member member = new Member();
        member.setUsername(registerRequest.getUserName());
        member.setEmail(registerRequest.getEmail());
        //password通过md5加密处理
        String userPassword = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
        member.setPassword(userPassword);
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);

        int effectRows = memberMapper.insert(member);
        if(effectRows != 1){
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        //向用户验证表中插入一条记录
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(member.getUsername());
        String key = member.getUsername() + member.getPassword() + UUID.randomUUID();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        int effect = userVerifyMapper.insert(userVerify);
        if(effect != 1){
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        //发送用户激活邮件
        //TODO:消息队列
        new Thread(){
            @Override
            public void run(){
                sendEmail(uuid, registerRequest);
            }
        }.start();
        //打印日志
        log.info("用户注册成功，注册参数request:{}", JSON.toJSONString(registerRequest));
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }
    /*
    * @Author Chunk
    * @Description 发送用户激活邮件
    * @Date 16:07 2021/4/21
    * @Param [uuid, registerRequest]
    * @return void
    **/
    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("CSMAll用户激活");
        mailMessage.setFrom("1161098309@qq.com");
        mailMessage.setTo(registerRequest.getEmail());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://localhost:8080/user/verify?uid=").append(uuid)
                .append("&username=").append(registerRequest.getUserName());
        mailMessage.setText(stringBuilder.toString());

        mailSender.send(mailMessage);
    }

    //验证用户名是否重复
    private void validUserNameRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",registerRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(members)){
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
